package com.shouhuobao.bhi.collectpoint;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.collectplus.express.BaseActivityWithSearch;
import com.collectplus.express.R;
import com.collectplus.express.app.Intents;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.SerachStationBean;
import com.collectplus.express.model.ServicePointBean;
import com.collectplus.express.view.CircleImageView;
import com.shouhuobao.bhi.loc.BaiduLocationService;

import java.util.ArrayList;

import droid.frame.app.Callback;
import droid.frame.umeng.UMeng;
import droid.frame.utils.Android;
import droid.frame.utils.lang.Str;

/**
 * 服务网点地图模式
 *
 * @author coffee<br>
 *         2016-12-5下午1:37:43
 */
public class ServicePointMapActivity extends BaseActivityWithSearch implements OnClickListener {

    //    private CollectMapGallery mGallery;
    private ViewPager mViewPager;

    private MapView mMapView;
    private BaiduMap mBaiduMap;

    // 选中或未选中状态
    //驿站
    private BitmapDescriptor mStoreSelectedPic;
    private BitmapDescriptor mStoreUnSelectedPic;
    //柜子
    private BitmapDescriptor mBoxSelectedPic;
    private BitmapDescriptor mBoxUnSelectedPic;

    private ArrayList<ServicePointBean> items;
    // 当前位置
    private BDLocation mCurrentLocation;

    private Intent mLocationService;
    ViewPagerAdapter adapter = null;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        items = (ArrayList<ServicePointBean>) getIntent().getSerializableExtra("items");
        super.onCreate(savedInstanceState);
        mLocationService = new Intent();
        mLocationService.setClass(getContext(), BaiduLocationService.class);
        mLocationService.putExtra("msgId", MsgID.location_service_point_map);
        startService(mLocationService);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.service_point_map);
        super.findViewById();
        getAppTitle().setCommonTitle("投递点");

        // 网点选中、未选中时在地图呈现的图标
        mStoreSelectedPic = BitmapDescriptorFactory.fromResource(R.drawable.collect_point_store_selected);
        mStoreUnSelectedPic = BitmapDescriptorFactory.fromResource(R.drawable.collect_point_store_unselected);
        //柜子
        mBoxSelectedPic = BitmapDescriptorFactory.fromResource(R.drawable.collect_point_box_selected);
        mBoxUnSelectedPic = BitmapDescriptorFactory.fromResource(R.drawable.collect_point_box_unselected);

        findViewById(R.id.point_location_center).setOnClickListener(this);

        // ViewPager
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setOffscreenPageLimit(items.size());
        adapter = new ViewPagerAdapter();
        mViewPager.setAdapter(adapter);
        // 子页间隔
        mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.viewpager_margin));
        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                setMyMapStatusChangeListener(true);
                ServicePointBean item = items.get(arg0);
                // 调整地图
                LatLng llB = new LatLng(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(llB);
                mBaiduMap.animateMapStatus(u);
                setMyMapStatusChangeListener(false);
                //
                for (int i = 0; i < mMarks.size(); i++) {
                    if (i == arg0) {
                        //柜子
                        if (item.getType() == 2) {
                            mMarks.get(i).setIcon(mBoxSelectedPic);
                        } else {
                            mMarks.get(i).setIcon(mStoreSelectedPic);
                        }
                        mMarks.get(i).setZIndex(10);
                    } else {
                        if (item.getType() == 2) {
                            mMarks.get(i).setIcon(mBoxUnSelectedPic);
                        } else {
                            mMarks.get(i).setIcon(mStoreUnSelectedPic);
                        }
                        mMarks.get(i).setZIndex(9);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        //         mGallery = (CollectMapGallery) findViewById(R.id.gallery);
        // mGallery.setSpacing(16);
        // mGallery.requestDisallowInterceptTouchEvent(true);
        // mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
        //
        // @Override
        // public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // setMyMapStatusChangeListener(true);
        // ServicePointBean item = (ServicePointBean) parent.getItemAtPosition(position);
        // // 调整地图
        // LatLng llB = new LatLng(Double.parseDouble(item.getPostStationBDLatitude()), Double.parseDouble(item.getPostStationBDLongitude()));
        // MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(llB);
        // mBaiduMap.animateMapStatus(u);
        // setMyMapStatusChangeListener(false);
        // //
        // for (int i = 0; i < mMarks.size(); i++) {
        // if (i == position) {
        // mMarks.get(i).setIcon(mStoreSelectedPic);
        // } else {
        // mMarks.get(i).setIcon(mStoreUnSelectedPic);
        // }
        // }
        // }
        //
        // @Override
        // public void onNothingSelected(AdapterView<?> parent) {
        // //
        // }
        // });

        initMapView();

        handleGalleryAdapter(items);

        //
        setSearchCallback(new Callback() {
            @Override
            public void execute(Object... result) {
                Android.hideSoftInput(getContext());
                SerachStationBean.ResultsBean item = (SerachStationBean.ResultsBean) result[0];
                UMeng.click(getContext(), "servicePoint_serach_click");
                showLoadingDialog("查询中");
                AppHttp.getInstance().servicePointSearchByLocation(item.getLocation().getLng(), item.getLocation().getLat());
            }
        });
        //
        final ImageView favorite = (ImageView) findViewById(R.id.service_point_favorite);
        favorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityWhenLogin(ServicePointFavoriteActivity.class);
            }
        });
        // 地图模式
        final ImageView mode = (ImageView) findViewById(R.id.service_point_mode);
        mode.setImageResource(R.drawable.icon_list);
        mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 切换搜索和非搜索视图
        setSearchSwitch(new Callback() {
            @Override
            public void execute(Object... result) {
                // 非搜索模式
                if (Boolean.TRUE.equals(result[0])) {
                    favorite.setVisibility(View.VISIBLE);
                    mode.setVisibility(View.VISIBLE);
                } else {
                    favorite.setVisibility(View.GONE);
                    mode.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initMapView() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView_point_find);
        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);
            // 隐藏缩放按键 ZoomControl
            if (child instanceof ImageView || child instanceof ZoomControls) {
                child.setVisibility(View.INVISIBLE);
            }
        }
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        mBaiduMap.setMapStatus(msu);
        setMyMapStatusChangeListener(true);
    }

    private void setMyMapStatusChangeListener(boolean isNull) {
        if (isNull) {
            mBaiduMap.setOnMapStatusChangeListener(null);
        } else {
            getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBaiduMap.setOnMapStatusChangeListener(listener);
                }
            }, 1000);
        }
    }

    private OnMapStatusChangeListener listener = new OnMapStatusChangeListener() {

        @Override
        public void onMapStatusChangeStart(MapStatus status) {
        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

        }

        @Override
        public void onMapStatusChangeFinish(MapStatus status) {
            if ((int) status.bound.southwest.latitude > 1) {
                // mapview 中心点
                double centerLat = status.target.latitude;
                double centerLong = status.target.longitude;
                //
                AppHttp.getInstance().servicePointSearchByMap(centerLong, centerLat);
            }
        }

        @Override
        public void onMapStatusChange(MapStatus status) {

        }
    };

    private void handleGalleryAdapter(ArrayList<ServicePointBean> items) {
        // ServicePointAdapter adapter = new ServicePointAdapter(getContext(), items);
        // mGallery.setAdapter(adapter);
        addMarkToMap();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 单击图标、移动到当前位置
            case R.id.point_location_center:
                LatLng ll = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
                break;
            default:
                super.onClick(v);
        }
    }

    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 获取当前位置
            case MsgID.location_service_point_map:
                mCurrentLocation = (BDLocation) msg.obj;
                LatLng ll = null;
                if (mCurrentLocation == null) {
                    showToast("定位失败");
                    return true;
                } else {
                    if (AppConfig.isOtherCity != 0) {
                        mCurrentCityName = "衡水市";
                        ll = new LatLng(AppConfig.getOhterCityLat(), AppConfig.getOhterCityLng());
                    } else {
                        mCurrentCityName = mCurrentLocation.getCity();
                        ll = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                    }
                    if (isNotEmpty(mCurrentCityName)) {
                        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                        mBaiduMap.animateMapStatus(u);
                        // *** 一秒钟以后再设置
                        setMyMapStatusChangeListener(false);
                    } else {
                        showToast("定位失败");
                    }
                }
                return true;
            // 按照地图查询
            case MsgID.service_point_search_by_map:
                cancelLoadingDialog();
                final AppResult<ServicePointBean> result = JSON.parseList(msg.obj, ServicePointBean.class);
                if (result.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handleGalleryAdapter(result.getResultList());
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            case MsgID.service_point_search_by_location:
                cancelLoadingDialog();
                final AppResult<ServicePointBean> result1 = JSON.parseList(msg.obj, ServicePointBean.class);
                if (result1.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            items.clear();
                            items.addAll(result1.getResultList());
                            adapter.notifyDataSetChanged();
                            handleGalleryAdapter(result1.getResultList());
                        }
                    });
                } else {
                    showToast(result1.getMessage());
                }
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    private ArrayList<Marker> mMarks = new ArrayList<Marker>();

    private void addMarkToMap() {
        // ...
        if (mMarks.size() > 0) {
            mMapView.getMap().clear();
            mMarks.clear();
        }

        for (int i = 0; i < items.size(); i++) {
            makeMarker(i, true);
        }

        mMapView.getMap().setOnMarkerClickListener(new OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker arg0) {
                int position = arg0.getExtraInfo().getInt("point");
                //                 mGallery.setSelection(position);
                mViewPager.setCurrentItem(position);
                mMarks.get(position).setZIndex(10);
                return false;
            }
        });
    }

    public Marker makeMarker(int position, boolean isSelected) {
        ServicePointBean item = items.get(position);
        LatLng llB = new LatLng(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
        OverlayOptions ooB = null;
        if (position == 0) {
            //柜子
            if (item.getType() == 2) {
                ooB = new MarkerOptions().position(llB).icon(mBoxSelectedPic).zIndex(10).draggable(true);
            } else {//驿站
                ooB = new MarkerOptions().position(llB).icon(mStoreSelectedPic).zIndex(10).draggable(true);
            }
        } else {
            //柜子
            if (item.getType() == 2) {
                ooB = new MarkerOptions().position(llB).icon(mBoxUnSelectedPic).zIndex(9).draggable(true);
            } else {//驿站
                ooB = new MarkerOptions().position(llB).icon(mStoreUnSelectedPic).zIndex(9).draggable(true);
            }
        }
        Overlay overlay = mMapView.getMap().addOverlay(ooB);
        Marker marker = (Marker) (overlay);
        Bundle bundle = new Bundle();
        bundle.putInt("point", position);
        marker.setExtraInfo(bundle);
        mMarks.add(marker);
        return marker;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        super.onDestroy();
    }

    class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {

            return items == null ? 0 : items.size();
        }

        @Override
        public float getPageWidth(int position) {
            return 1.f;// 默认值
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {

            return (view == object);
        }

        @Override
        public int getItemPosition(Object object) {
            return items != null && items.size() == 0 ? POSITION_NONE : super.getItemPosition(object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            LinearLayout convertView = (LinearLayout) ServicePointMapActivity.this.getLayoutInflater().inflate(R.layout.service_point_item_map, null);
            ImageView logo = (ImageView) convertView.findViewById(R.id.service_point_logo_icon);
            CircleImageView logoImage = (CircleImageView) convertView.findViewById(R.id.service_point_logo);
            TextView name = (TextView) convertView.findViewById(R.id.service_point_name);
            TextView type1 = (TextView) convertView.findViewById(R.id.service_point_type1);
            TextView type2 = (TextView) convertView.findViewById(R.id.service_point_type2);
            TextView address = (TextView) convertView.findViewById(R.id.service_point_address);
            View serviceGoto = convertView.findViewById(R.id.service_point_goto);
            View call = convertView.findViewById(R.id.service_point_call);
            final ServicePointBean item = items.get(position);
            // 驿站
            if (item.isStation()) {
                ((ViewGroup) call.getParent()).setVisibility(View.VISIBLE);
                if (Str.isEmpty(item.getHeadImage())) {
                    logo.setVisibility(View.VISIBLE);
                    logoImage.setVisibility(View.GONE);
                    logo.setImageResource(R.drawable.service_point_logo2);

                } else {
                    logo.setVisibility(View.GONE);
                    logoImage.setVisibility(View.VISIBLE);
                    AppLogic.getInstance().loadImage(item.getHeadImage(), logoImage);
                    logoImage.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DialogMgr.showLargeStationPhoto(getContext(), item.getHeadImage());
                        }
                    });
                }
            } else {
                ((ViewGroup) call.getParent()).setVisibility(View.GONE);
                logo.setVisibility(View.VISIBLE);
                logoImage.setVisibility(View.GONE);
                logo.setImageResource(R.drawable.service_point_logo1);
            }
            name.setText(item.getName());
            if (item.getType() == 2) {
                type1.setVisibility(View.VISIBLE);
                type2.setVisibility(View.VISIBLE);
                type1.setText("代收点");
                type2.setText("投递点");
            } else {
                type1.setVisibility(View.GONE);
                type2.setVisibility(View.VISIBLE);
                if (item.getType() == 1) {
                    type2.setText("投递点");
                } else {
                    type2.setText("代收点");
                }
            }
            address.setText(item.getAddress());
            // 进入网点详情
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), ServicePointDetailsActivity.class);
                    intent.putExtra("item", item);
                    startActivity(intent);
                }
            });
            // 导航
            serviceGoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intents.navigation(item.getLatitude(), item.getLongitude(), //
                            item.getGdlatitude(), item.getGdLongitude(), item.getAddress());
                }
            });
            // 拨打电话
            call.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intents.dialOrCall(item.getPhone());
                }
            });
            ((ViewPager) container).addView(convertView, position);
            return convertView;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

            ((ViewPager) container).removeView((LinearLayout) object);

        }

    }

}
